@file:Suppress("DEPRECATION")

package com.juku2024.juku.widget

import android.content.Context
import android.content.res.TypedArray
import android.text.TextUtils
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.TextView
import androidx.constraintlayout.widget.ConstraintLayout
import com.juku2024.juku.R
import com.juku2024.juku.tools.AppUtils

class HeaderView(context: Context, attrs: AttributeSet) : ConstraintLayout(context, attrs) {

    private val tvEdit: TextView
    private val tvTitle: TextView
    private val backLayout: View
    init {
        val rootView = LayoutInflater.from(context).inflate(R.layout.view_header, this, true)
        tvEdit = rootView.findViewById(R.id.tvEdit)
        tvTitle = rootView.findViewById(R.id.tvTitle)
        backLayout = rootView.findViewById(R.id.backLayout)


        val ta: TypedArray = context.obtainStyledAttributes(attrs, R.styleable.HeaderView)
        val title = ta.getString(R.styleable.HeaderView_title)
        val edit = ta.getString(R.styleable.HeaderView_edit)
        val isShowBack = ta.getBoolean(R.styleable.HeaderView_isShowBack, true)
        ta.recycle()
        tvTitle.text = title
        backLayout.setOnClickListener {
            AppUtils.findActivity(context)?.onBackPressed()
        }
        if (TextUtils.isEmpty(edit)) {
            tvEdit.visibility = View.GONE
        }  else {
            tvEdit.visibility = View.VISIBLE
            tvEdit.text = edit
        }
        if (!isShowBack) {
            backLayout.visibility = View.GONE
        }
    }


    fun setOnEditClickListener(editClickListener: OnClickListener){
        tvEdit.setOnClickListener(editClickListener)
    }

    fun getMenuText(): String{
        return tvEdit.text.toString()
    }

    fun setTitle(title: String) {
        tvTitle.text = title
    }

    fun setMenuText(title: String?) {
        if (TextUtils.isEmpty(title)) {
            tvEdit.visibility = View.GONE
        }  else {
            tvEdit.visibility = View.VISIBLE
            tvEdit.text = title
        }
    }

    fun hideEditView() {
        tvEdit.visibility = View.GONE
    }

}